
import { requestApi } from "../../utils/util";
import { API_URLS } from '../../api/index.js';

const deviceTreeMixin = {
  data() {
    return {
      treeData: [],
      expandedKeys: [], // 展开的节点
      pageNo: 1
    };
  },
  methods: {
    /**
     * 获取树节点数据，分地区数据和最底层的设备数据
     * @param parentId - 节点id，不传或为空表示请求根节点
     * @param hasChildren - 是否获取区域列表
     * @param isGetDeviceList - 是否获取设备列表，请求树结构中的地区数据和设备数据的接口不同
     * @param showLoading - 请求数据时是否显示加载loading
     * @param refreshNode - 刷新当前节点
     */
    getTreeData(params = {}) {
      this.checkedKeys = []
      const {
        parentId = '',
        parentRegionCode = '',	
        treeType = 2,
        isGetDeviceList = false,
        isMoreDevice = false,
        hasChildren,
        showLoading = false,
        refreshNode,
        preDevice = [],
        prePageNo = 1,
        isCheckBox = false
      } = params;
      let pRegion = [];
      let pDevice = [];
      if (!parentId || hasChildren) {
        // 获取地区/分组列表（有子节点）
        let params = {
          // aiAbilityType: this.treeType,
          // cloudType: 1 // 1：端云，2云端
          // regionId: ''
        };
        if (parentId) {	
          params.regionId = parentId;	
          params.parentRegionCode = parentRegionCode;	
          // 自定义监控目录树	
          if (treeType === 2) {	
            params.treeType = 2;	
            pRegion.push(this.getRegionList(params, 2, showLoading || !parentId));	
          } else {	
            // 固定业务树	
            params.treeType = 6;	
            pRegion.push(this.getRegionList(params, 6, showLoading || !parentId));	
          }	
        } else {	
          // 自定义监控目录树	
          params.regionId = 0;	
          params.treeType = 2;	
          pRegion.push(this.getRegionList(params, 2, showLoading || !parentId));	
          // 固定业务树	
          params.regionId = '';	
          params.treeType = 6;	
          pRegion.push(this.getRegionList(params, 6, showLoading || !parentId));	
        }
      }
      if (isGetDeviceList) {
        // 获取设备列表（无子节点）
        let params = {
          pageSize: 50, // 设置一个大值，一次请求所有数据
          pageNo: prePageNo,
          // aiAbilityType: this.treeType,
          regionId: parentId,
          // cloudType: 1, // 1：端云，2云端
          // status: 1 // 1 需要 2 不需要
          aiType: 9
        };
        if (parentId) {	
          params.regionId = parentId;	
          // 自定义监控目录树	
          if (treeType === 2) {	
            // 自定义监控目录树	
            params.treeType = 2;	
            pDevice.push(	
              this.getRegionDeviceList(	
                params,	
                showLoading || !parentId,	
                isMoreDevice,	
                preDevice,	
                isCheckBox	
              )	
            );	
          } else {	
            // 固定业务树, 不是顶层不请求	
            params.treeType = 6;	
            pDevice.push(	
              this.fgetRegionDeviceList(	
                params,	
                showLoading || !parentId,	
                isMoreDevice,	
                preDevice,	
                isCheckBox	
              )	
            );	
          }	
        } else {	
          // 自定义监控目录树	
          params.treeType = 2;	
          pDevice.push(	
            this.getRegionDeviceList(	
              params,	
              showLoading || !parentId,	
              isMoreDevice,	
              preDevice,	
              isCheckBox	
            )	
          );	
          // 固定业务树	
          params.treeType = 6;	
          pDevice.push(	
            this.fgetRegionDeviceList(	
              params,	
              showLoading || !parentId,	
              isMoreDevice,	
              preDevice,	
              isCheckBox	
            )	
          );	
        }
      }

      return Promise.all([...pRegion, ...pDevice]).then((res) => {
        console.log('res',res);
        let nodeList = res?.length === 2 ? res[0].concat(res[1]) : res?.length === 1 ? res[0] : [];
        if (!parentId) {
          // 根节点数据
          this.treeData = [...nodeList];
        } else {
          // 添加子节点
          let updateParent = {};
          if (refreshNode) {	
            this.getNodeDeviceNum(parentId, treeType, parentRegionCode, showLoading).then(	
              ({ deviceCount }) => {	
                updateParent = { deviceCount: deviceCount };	
                let { arr } = this.insertTreeChildren(	
                  isMoreDevice,	
                  this.treeData,	
                  parentId,	
                  nodeList,	
                  updateParent	
                );	
                this.treeData = [...arr];	
              }	
            );	
          } else {
            let { arr } = this.insertTreeChildren(isMoreDevice, this.treeData, parentId, nodeList);
            this.treeData = [...arr];
          }
        }
        // console.log('this.treeData',this.treeData);
        return;
      });
    },

    // 获取节点区域节点列表
    getRegionList(params, treeType, showLoading) {
      return new Promise((resolve) => {
        const { regionId, parentRegionCode } = params;
        let parentId = regionId || '';
        console.log('API_URLS====',API_URLS);
        requestApi({
          url: API_URLS.getRegions,
          method: 'post',
          data: { ...params },
          headers:{
            AccessToken: this.cardInfo.accessToken
          }
        }).then((res) => {
          console.log(res);
            if (res?.code === 0 && res.data) {
              let list = res.data.map((item) => {
                return {
                  ...item,
                  key: '' + item.id,
                  isLeaf: false,
                  selectable: true,
                  // checkable: false,
                  title: item.name,
                  // onlineDeviceCount: item.onlineDeviceCount || 0,
                  deviceCount: item.totalCount || 0,
                  scopedSlots: {
                    title: 'title',
                    icon: 'titleIcon'
                  },
                  keyPath: parentId ? '' : '' + item.id,
                  pathName: parentId ? '' : '' + item.name,
                  hasChildren: item.hasChildren,
                  pid: parentId,	
                  pregionCode: parentRegionCode,	
                  regionCode: item.regionCode,	
                  treeType: treeType
                };
              });
              let clist = list.filter((el) => el.treeType === 2);

              // 获取各节点设备数量
              this.updateListDeviceNum(clist, 2, showLoading)
                .then((r) => {
                  list = r;
                })
                .finally(() => { });	
              let flist = list.filter((el) => el.treeType === 6);	
              // 获取各节点设备数量	
              this.fupdateListDeviceNum(flist, 6, showLoading)	
                .then((r) => {	
                  list = [...list, ...r];	
                })	
                .finally(() => {
                  resolve(list);
                  // resolve([]);// 测试空状态
                });

            } else {
              resolve([]);
            }
          })
          .catch(() => {
            resolve([]);
          });
      });
    },

    // 获取设备列表
    getRegionDeviceList(params, showLoading, isMoreDevice, preDevice, isCheckBox) {
      const { regionId } = params;
      return requestApi({
        url: API_URLS.getDevicePackageList,
        method: 'post',
        data: { ...params },
        headers:{
          AccessToken: this.cardInfo.accessToken
        }
      }).then((res) => {
          if (res && res.code === 0) {
            let deviceList = res.data?.list || [];
            let list = [];
            // 加载更多就合并数据
            if (isMoreDevice) {
              deviceList = [...preDevice, ...deviceList];
            }
            deviceList.map((item, index) => {
              list.push({
                ...item,
                key: '' + item.deviceCode,
                isLeaf: true,
                selectable: true,
                checkable: isCheckBox,
                disableCheckbox:	
                  typeof this.checkDisableFn === 'function' ? this.checkDisableFn(item) : false,
                title: item.deviceName,
                scopedSlots: {
                  title: 'title',
                  icon: 'deviceIcon',
                  switcherIcon: 'deviceSwitcherIcon'
                },
                pid: regionId,	
                treeType: 2,
              });
              if (deviceList.length - 1 === index && params.pageNo < res.data.totalPage) {
                list.push({
                  ...item,
                  key: '',
                  isLeaf: true,
                  selectable: true,
                  checkable: false,
                  deviceCode: '-',
                  title: '加载更多',
                  scopedSlots: {
                    title: 'title'
                  },
                  pid: regionId,
                  isLast: deviceList.length - 1 === index && params.pageNo < res.data.totalPage,
                  preDevice: deviceList,
                  prePageNo: params.pageNo,	
                  treeType: 2,
                });
              }
            });
            return list;
          } else {
            return [];
          }
        });
    },
    // 获取设备列表（固定业务树）	
    fgetRegionDeviceList(params, showLoading, isMoreDevice, preDevice, isCheckBox) {	
      const { regionId } = params;	
      return requestApi({
        url: API_URLS.getDevicePackageList,
        method: 'post',
        data: { ...params },
        headers:{
          AccessToken: this.cardInfo.accessToken
        }
      }).then((res) => {	
          if (res && res.code === 0) {	
            let deviceList = res.data?.list || [];	
            let list = [];	
            // 加载更多就合并数据	
            if (isMoreDevice) {	
              deviceList = [...preDevice, ...deviceList];	
            }	
            deviceList.map((item, index) => {	
              list.push({	
                ...item,	
                key: '' + item.deviceCode,	
                isLeaf: true,	
                selectable: true,	
                checkable: isCheckBox,	
                disableCheckbox:	
                  typeof this.checkDisableFn === 'function' ? this.checkDisableFn(item) : false,	
                title: item.deviceName,	
                scopedSlots: {	
                  title: 'title',	
                  icon: 'deviceIcon',	
                  switcherIcon: 'deviceSwitcherIcon'	
                },	
                pid: regionId,	
                treeType: 6,	
              });	
              if (deviceList.length - 1 === index && params.pageNo < res.data.totalPage) {	
                list.push({	
                  ...item,	
                  key: '',	
                  isLeaf: true,	
                  selectable: true,	
                  checkable: false,	
                  deviceCode: '-',	
                  title: '加载更多',	
                  scopedSlots: {	
                    title: 'title'	
                  },	
                  pid: regionId,	
                  treeType: 6,	
                  isLast: deviceList.length - 1 === index && params.pageNo < res.data.totalPage,	
                  preDevice: deviceList,	
                  prePageNo: params.pageNo,	
                });	
              }	
            });	
            return list;	
          } else {	
            return [];	
          }	
        });	
    },
    // 批量获取节点设备数量
    updateListDeviceNum(regionList, showLoading) {
      return new Promise((resolve) => {
        if (!regionList || regionList.length === 0) return resolve([]);
        let regionIds = regionList
          .map((item) => {
            return item.id;
          })
          .join(',');
        let params = {
          regionIds: regionIds
          // aiAbilityType: this.treeType,
          // cloudType: 1// 1：端云，2云端
        };
        requestApi({
          url: API_URLS.deviceCount,
          method: 'post',
          data: { ...params },
          headers:{
            AccessToken: this.cardInfo.accessToken
          }
        }).then((res) => {
            if (res?.data?.length > 0) {
              regionList = regionList.map((item) => {
                let numInfo = res.data.find((itm) => itm.regionId === item.id);
                numInfo && (item.deviceCount = parseInt(numInfo.totalCount) || 0);
                numInfo && (item.checkable = !this.isLive && item.hasChildren === 0 && numInfo.totalCount > 0);
                return item;	
              });	
            }	
            resolve(regionList);	
          });	
      });	
    },	
    // 批量获取节点设备数量(固定业务树) 只能区分开，有坑	
    fupdateListDeviceNum(regionList, showLoading) {	
      return new Promise((resolve) => {	
        if (!regionList || regionList.length === 0) return resolve([]);	
        // 判断固定业务树是不是顶层	
        let fregionIdsIsTop =	
          regionList.findIndex((el) => el.pid === '0' || el.pid === '' || el.pid === null) !== -1;	
        // 过滤找到第一层的regionCode	
        let fregion = regionList.find((item) => item.pregionCode);	
        let params = {	
          regionIds: fregionIdsIsTop ? '' : fregion.pregionCode,	
          treeType: 6	
        };	
        requestApi({
          url: API_URLS.deviceCount,
          method: 'post',
          data: { ...params },
          headers:{
            AccessToken: this.cardInfo.accessToken
          }
        }).then((res) => {	
            if (res?.data?.length > 0) {	
              regionList = regionList.map((item) => {	
                let numInfo = res.data.find((itm) => itm.regionId === item.regionCode);	
                numInfo && (item.deviceCount = parseInt(numInfo.totalCount) || 0);	
                numInfo && (item.checkable = !this.isLive && item.hasChildren === 0 && numInfo.totalCount > 0);
                console.log('item.checkable',item.checkable);
                return item;
              });
            }
            resolve(regionList);
          });
      });
    },

    // 获取某个节点设备数量
    getNodeDeviceNum(regionId, treeType, parentRegionCode, showLoading) {
      let params = {
        treeType: treeType
      };
      if (treeType === 2) {	
        params.regionIds = regionId;	
      }
      return requestApi({
        url: API_URLS.deviceCount,
        method: 'post',
        data: { ...params },
        headers:{
          AccessToken: this.cardInfo.accessToken
        }
      }).then((res) => {
          if (res?.data?.length > 0) {
            let count = res.data.find((itm) => itm.regionId === regionId)?.totalCount || 0;
            return {
              deviceCount: count
            };
          } else {
            return {
              deviceCount: 0
            };
          }
        });
    },

    // 多级树结构插入子节点数据
    insertTreeChildren(isMoreDevice, arr, parentId, children, updateParent) {
      let flag = false;
      if (arr.length > 0) {
        for (let i = 0, len = arr.length; i < len; i++) {
          if (arr[i].id === parentId) {
            updateParent && (arr[i] = { ...arr[i], ...updateParent }); // 更新父节点属性
             // 区分刷新节点还是加载设备	
            let isRegion = arr[i].children && arr[i].children.find((el) => el.regionCode);	
            let isDevice = arr[i].children && arr[i].children.find((el) => el.deviceCode);	
            let isDR = false;	
            if (isMoreDevice) {	
              isDR = isDevice;	
            } else {	
              isDR = isRegion && isDevice;	
            }
            // 如果节点有区域
            if (isDR) {
              let oldArr = arr[i].children;
              // 区域数据
              let personFilter = oldArr.filter((element) => !element.deviceCode);
              arr[i].children = [...personFilter, ...children] || [];
            } else {
              arr[i].children = children || [];
            }
            // 插入keyPath
            arr[i].children.forEach((item) => {
              item.keyPath = `${arr[i].keyPath}/${item.key}`;
              item.pathName = `${arr[i].pathName}/${item.name || item.deviceName}`;
            });
            flag = true;
            break;
          } else if (arr[i].children && arr[i].children.length > 0) {
            flag = this.insertTreeChildren(isMoreDevice, arr[i].children, parentId, children).flag;
            if (flag) {
              break;
            }
          }
        }
      }
      return {
        flag,
        arr
      };
    },

    // 展开节点
    onExpand(expandedKeys, event) {
      this.expandedKeys = expandedKeys;
      if (event) {
        this.onLoadData(event.node);
      }
    },

    // 点击树节点
    clickNode(dataRef) {
      if (dataRef && dataRef.deviceCode) return;
      // this.switchExpand(dataRef.key);
    },

    // 切换展开/合并节点
    switchExpand(key) {
      let index = this.expandedKeys.indexOf(key);
      if (index > -1) {
        this.expandedKeys.splice(index, 1); // 合并
      } else {
        this.expandedKeys.push(key); // 展开
      }
    }
  }
};

export default deviceTreeMixin;
